import React, { useState } from 'react'
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell
} from '@/components/ui/table'
import { Piece } from '@/types/piece'
import { Badge } from '@/components/ui/badge'
import { Avatar } from '@/components/ui/avatar'
import ImageSliceViewer from '@/components/ui/image-slice-viewer'
import PieceDialog from './piece'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger
} from '@/components/ui/tooltip'

interface EquipProps {
  pieces: (Piece | undefined)[]
  onChange: (pieces: (Piece | undefined)[]) => void
  backgroundColor?: string // 背景颜色
  columns?: number // 列数 默认9列
  type?: number // 1:装备 2:首饰
  name?: string
  columnNames?: string[] // 新增：每列的名称
}

const Equip: React.FC<EquipProps> = ({
  pieces,
  onChange,
  columns = 9,
  type = 1,
  // backgroundColor = 'bg-green-100',
  columnNames
}) => {
  const rows = 5
  const cellSize = 60 // 单元格宽高都为60px，正方形
  // 生成二维数组，列优先

  // 最近选择的碎片，最多5个
  const [recentPieces, setRecentPieces] = useState<Piece[]>([])
  // 记录最近选择的碎片
  const handleSelect = (newPiece: Piece | undefined, index: number) => {
    const newPieces = [...pieces]
    newPieces[index] = newPiece
    onChange(newPieces)
    if (newPiece) {
      setRecentPieces((prev) => {
        // 去重，最新的放前面
        const filtered = prev.filter((p) => p.id !== newPiece.id)
        return [newPiece, ...filtered].slice(0, 6)
      })
    }
  }

  return (
    <div
      className="relative flex flex-col items-center justify-center"
      style={{ height: rows * cellSize + 24, minHeight: rows * cellSize + 24 }}
    >
      {/* 每列之间的样式已去除 */}
      {/* 美化表头 */}
      {columnNames && columnNames.length === columns && (
        <div style={{ minWidth: columns * cellSize + (columns - 1) * 2 }}>
          <Table
            className="w-full table-fixed"
            style={{ width: columns * cellSize + (columns - 1) * 2 }}
          >
            <TableHeader>
              <TableRow className="border-0 hover:bg-transparent">
                {columnNames.map((col, colIdx) => (
                  <TableHead
                    key={col}
                    className="relative h-[22px] w-[60px] p-0 text-center"
                    style={{
                      marginRight: colIdx < columns - 1 ? '2px' : '0'
                    }}
                  >
                    <div className="group relative flex size-full items-center justify-center overflow-hidden rounded-md bg-gradient-to-b from-slate-50 to-slate-100 shadow-sm transition-all duration-200 hover:from-slate-100 hover:to-slate-200 hover:shadow-md dark:from-slate-800 dark:to-slate-900 dark:hover:from-slate-700 dark:hover:to-slate-800">
                      {/* 装饰性边框 */}
                      <div className="absolute inset-0 rounded-md border border-slate-200/60 dark:border-slate-700/60" />

                      {/* 顶部高光 */}
                      <div className="absolute inset-x-1 top-0.5 h-px bg-gradient-to-r from-transparent via-white/40 to-transparent dark:via-white/20" />

                      {/* 文字内容 */}
                      <span className="relative z-10 select-none text-xs font-medium tracking-wide text-slate-700 transition-colors duration-200 group-hover:text-slate-900 dark:text-slate-300 dark:group-hover:text-slate-100">
                        {col}
                      </span>

                      {/* 底部阴影 */}
                      <div className="absolute inset-x-0 bottom-0 h-px bg-gradient-to-r from-transparent via-slate-300/30 to-transparent dark:via-slate-600/30" />
                    </div>
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
          </Table>
        </div>
      )}
      <div
        style={{
          minWidth: columns * cellSize + (columns - 1) * 2,
          width: '100%'
        }}
      >
        <Table style={{ width: columns * cellSize + (columns - 1) * 2 }}>
          <TableBody>
            {Array.from({ length: rows }).map((_, rowIdx) => (
              <TableRow
                key={rowIdx}
                className="h-[60px] max-h-[60px] min-h-[60px] border-0 hover:bg-transparent"
              >
                {Array.from({ length: columns }).map((_, colIdx) => {
                  const idx = colIdx * rows + rowIdx
                  const piece = pieces[idx]
                  return (
                    <TableCell
                      key={colIdx}
                      className="group/column p-0 text-center align-middle transition-all duration-200 hover:bg-gray-50 hover:shadow-lg dark:hover:bg-gray-800/50"
                      style={{
                        marginRight: colIdx < columns - 1 ? '2px' : '0',
                        borderRadius: '4px'
                      }}
                    >
                      <div className="group relative box-border size-[60px] cursor-pointer overflow-hidden border-none p-0 text-center align-middle transition-all duration-200">
                        <PieceDialog
                          piece={piece}
                          type={type}
                          recentPieces={recentPieces}
                          onSelect={(newPiece) => handleSelect(newPiece, idx)}
                        >
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <div className="relative flex size-full flex-col items-center justify-center overflow-hidden transition-all duration-200 group-hover:z-20 group-hover/column:scale-[1.02] group-hover:scale-[1.08] group-hover/column:shadow-md group-hover:shadow-2xl group-hover:ring-2 group-hover:ring-blue-300 dark:group-hover:ring-blue-700">
                                  {piece ? (
                                    <>
                                      <Badge
                                        className="absolute right-0 top-0 z-20 flex min-h-[12px] min-w-[12px] select-none items-center justify-center rounded-[3px] bg-black/30 px-[3px] py-0 text-[9px] font-semibold leading-none text-white shadow-sm backdrop-blur-[1px]"
                                        style={{
                                          textShadow:
                                            '0 1px 2px rgba(0,0,0,0.4)'
                                        }}
                                      >
                                        {piece.score ? piece.score : '0'}
                                      </Badge>
                                      <div className="flex size-full max-h-[60px] min-h-[60px] flex-col">
                                        <div className="relative m-0 flex size-[60px] items-center justify-center p-0">
                                          <Avatar className="relative size-[60px] rounded-none">
                                            <ImageSliceViewer
                                              imageSliceId={piece.avatar}
                                              alt={piece.name}
                                              className="size-[60px] rounded-none object-cover"
                                              width={60}
                                              height={60}
                                            />
                                            {/* alias 仅文字描边，无蒙板 */}
                                            <span className="pointer-events-none absolute bottom-0 left-1/2 max-w-[90%] -translate-x-1/2 select-none truncate text-[11px] font-bold leading-[15px] tracking-wide text-white [text-shadow:0_0_2px_black,0_1px_4px_black,0_0_1px_black,0_0_1px_black]">
                                              {piece.alias}
                                            </span>
                                          </Avatar>
                                        </div>
                                      </div>
                                    </>
                                  ) : (
                                    <div className="flex size-full flex-col items-center justify-center rounded-none border border-dashed border-gray-300 bg-gradient-to-br from-gray-100 via-gray-50 to-gray-200 shadow-inner transition-all group-hover/column:border-gray-400 group-hover:border-blue-400 group-hover/column:bg-gray-100/80 group-hover:bg-blue-50/80 group-hover:shadow-xl dark:from-gray-800 dark:via-gray-900 dark:to-gray-800 dark:group-hover/column:border-gray-600 dark:group-hover:border-blue-600 dark:group-hover/column:bg-gray-700/40 dark:group-hover:bg-blue-900/40">
                                      <div className="flex flex-col items-center justify-center gap-1">
                                        <svg
                                          width="24"
                                          height="24"
                                          fill="none"
                                          viewBox="0 0 24 24"
                                          className="mb-1 opacity-30"
                                        >
                                          <rect
                                            x="4"
                                            y="4"
                                            width="16"
                                            height="16"
                                            rx="4"
                                            fill="currentColor"
                                            className="text-gray-300 dark:text-gray-700"
                                          />
                                          <path
                                            d="M8 12h8M12 8v8"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                            strokeLinecap="round"
                                            className="text-gray-400 dark:text-gray-500"
                                          />
                                        </svg>
                                        <span className="select-none text-[11px] font-medium text-gray-400 dark:text-gray-500">
                                          Socket {rowIdx + 1}
                                        </span>
                                      </div>
                                    </div>
                                  )}
                                </div>
                              </TooltipTrigger>
                              {piece && piece.name && (
                                <TooltipContent side="top">
                                  <strong>
                                    {piece.name}({piece.alias})
                                  </strong>
                                  <br /> {piece.describe}
                                </TooltipContent>
                              )}
                            </Tooltip>
                          </TooltipProvider>
                        </PieceDialog>
                      </div>
                    </TableCell>
                  )
                })}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}

export default Equip
